<template>
  <div>
    <h3>已购项目</h3>
    <PurchasedItemsTable
      class="tableStyle"
      :table-data="pageData"
      :column-headers="columnHeaders"
      :show-header="true"
    ></PurchasedItemsTable>
    <!-- page-size 每页显示条目个数  total 总条目数 -->
    <el-pagination
      class="announcementPagination"
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="tableData.length"
      :current-page.sync="currentPage"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
</template>

<script>
import PurchasedItemsTable from '@/components/Tables/PurchasedItemsTable.vue'
export default {
  name: 'PurchasedItems',
  components: {
    'PurchasedItemsTable': PurchasedItemsTable
  },
  // 后台交互，根据账户来获取其已购项目
  created () {
    this.ID = localStorage.getItem('userID')
    this.getPurchasedItems()
  },
  data () {
    return {
      ID: '',
      // totalTableLength: 0, // 获取通告总数目
      pageSize: 8, // page-size 每页显示条目个数
      currentPage: 1,
      search: '',
      columnHeaders: [ // 列表的头标签
        {prop: 'name', label: '名称'},
        {prop: 'price', label: '价格'},
        {prop: 'number', label: '数量'},
        {prop: 'status', label: '交易状态'}
      ],
      tableData: [
      ] // 存储通告数据
    }
  },
  computed: {
    // 设置当前页的显示
    pageData: function () {
      return this.tableData.slice(((this.currentPage) - 1) * this.pageSize, this.currentPage * this.pageSize)
    }
  },
  methods: {
    handleCurrentChange (currentPage) {
      this.currentPage = currentPage
    },
    getPurchasedItems () {
      let that = this
      let xmlhttp = new XMLHttpRequest()
      xmlhttp.open('POST', 'http://127.0.0.1:3100/users/getHistory')
      xmlhttp.setRequestHeader('content-type', 'application/json')
      let data = {id: this.ID}
      xmlhttp.onreadystatechange = function (res) {
        if (xmlhttp.readyState === 4) {
          if (xmlhttp.status === 200) {
            that.dealRes(xmlhttp.response)
          }
        }
      }
      xmlhttp.send(JSON.stringify(data))
    },
    dealRes (res) {
      let items = JSON.parse(res)
      for (var i = 0; i < items.length; i++) {
        let tem = {name: items[i].bookName, price: items[i].price, number: items[i].buyNum, status: items[i].dealStatus}
        this.tableData.push(tem)
      }
    }
  }
}
</script>

<style scoped>
  .tableStyle{
    margin-bottom: 2%;
    margin-left: 10%;
    width: 80%;
  }
</style>
